package com.rui.common.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Log4j2
public class IpUtil {

    private static final String REGION_DB = "ip2region.db";

    /**
     * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = null;
        String[] headers = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        for (String header : headers) {
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader(header);
            } else if (ip.length() > 15) {
                for (String str : ip.split(",")) {
                    if (!("unknown".equalsIgnoreCase(str))) {
                        ip = str;
                        break;
                    }
                }
            }
        }
        return StringUtils.isNotBlank(ip) ? ip : request.getRemoteAddr();
    }

    /**
     * 获取ip详细信息
     *
     * @param ip
     * @return
     */
    public static String getIpInfo(String ip) {
        String ipInfo = null;
        try {
            DbConfig config = new DbConfig();
            InputStream inputStream = IpUtil.class.getClassLoader().getResourceAsStream(REGION_DB);
            assert inputStream != null;
            byte[] bytes = IOUtils.toByteArray(inputStream);
            DbSearcher searcher = new DbSearcher(config, bytes);
            DataBlock dataBlock = searcher.memorySearch(ip);
            ipInfo = dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert ipInfo != null;
        return ipInfo.replace("|", "").replace("0", "");
    }
}
